package com.qdevelop.control.action;

import java.util.Map;

import com.qdevelop.control.bean.QueryBean;
import com.qdevelop.control.bean.SecurityUserBean;
import com.qdevelop.lang.QDevelopException;
import com.qdevelop.model.service.database.DBFactory;
import com.qdevelop.model.utils.QdevelopUtils;
import com.qdevelop.model.utils.UtilsFactory;

public class JsonAction extends QDevelopBaseAction {

	private static final long serialVersionUID = 7494536930134035018L;

	Object json;

	private SecurityUserBean getSecurityUserBean() throws QDevelopException {
		SecurityUserBean sub = null;
		if (UtilsFactory.isInterceptor) {
			sub = LoginAction.getLoginUserRoles();
			if (sub == null)
				throw new QDevelopException(UtilsFactory.propertiesUtils()
						.getProperty("JsonAction.noLogin.error.msg"));
		}
		return sub;
	}

	public String execute() throws Exception {
		try {
			SecurityUserBean sub = getSecurityUserBean();
			QueryBean qb = QdevelopUtils.getInstance().getQueryBean(
					this.getParamMap(), sub);
			json = DBFactory.getInstance().getQueryResult(qb);
		} catch (QDevelopException e) {
			json = e.getMessage();
		}
		return SUCCESS;
	}

	public String QueryDB() throws Exception {
		try {
			SecurityUserBean sub = getSecurityUserBean();
			QueryBean qb = QdevelopUtils.getInstance().getQueryBean(
					this.getParamMap(), sub);
			json = DBFactory.getInstance().getQueryResult(qb);
		} catch (QDevelopException e) {
			json = e.getMessage();
		}
		return SUCCESS;
	}

	public String multiQueryDB() throws Exception {
		try {
			getSecurityUserBean();
			QueryBean[] qb = QdevelopUtils.getInstance().getMultiQueryBean(
					this.getParamMap());
			json = DBFactory.getInstance().getMultiQueryResult(qb);
		} catch (QDevelopException e) {
			json = e.getMessage();
		}
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public String updateDB() throws Exception {
		try {
			SecurityUserBean sub = getSecurityUserBean();
			Map param = this.getParamMap();
			if (!this.isRepeatSubmit(param)) {
				QueryBean qb = QdevelopUtils.getInstance().getQueryBean(param,
						sub);
				json = DBFactory.getInstance().updateBySQL(qb);
			}
		} catch (QDevelopException e) {
			json = e.getMessage();
		}
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public String multiUpdateDB() throws Exception {
		try {
			getSecurityUserBean();
			Map param = this.getParamMap();
			if (!this.isRepeatSubmit(param)) {
				QueryBean[] qb = QdevelopUtils.getInstance().getMultiQueryBean(
						param);
				json = DBFactory.getInstance().updateBySQL(qb);
			}
		} catch (QDevelopException e) {
			json = e.getMessage();
		}
		return SUCCESS;
	}

	public Object getJson() {
		return json;
	}

	public void setJson(Object json) {
		this.json = json;
	}

}
